package com.yu.xcx.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.xcx.dto.Result;
import com.yu.xcx.entity.User;
import com.yu.xcx.mapper.UserMapper;
import com.yu.xcx.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String openId, String sekey, String nickName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("open_id",openId);
        int c = count(wrapper);
        User user = new User();
        user.setOpenId(openId);
        user.setSekey(sekey);
        user.setNickName(nickName);

        if (c < 1) {
            if (nickName == null){
                return null;
            }
            boolean flag = save(user);
//            int result = userMapper.savaUser(openId,sekey);
            if (!flag){
                return null;
            }
        }else if (nickName != null){
            update(user,wrapper);
        }
        return userMapper.getByOpenId(openId);
    }

    @Override
    public Result selectOpenId(String openId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",openId);
        User user = getOne(queryWrapper);
        if (user != null){
            return Result.ok(user);
        }else{
            return Result.fail("用户未注册过");
        }
    }

    @Override
    public Result selectById(Integer id) {
        return Result.ok(query().eq("id",id));
    }


}
